#!/usr/bin/python
import sys
import os
import pysvn

url = sys.argv[1]
location = sys.argv[2]

loginenter = False
sslenter = False
cleanup = 0
exitcode = 0

if len(sys.argv)>3:
	usr = sys.argv[3]
	pwd = sys.argv[4]
	comment = sys.argv[5]

def ssl_server_trust_prompt( trust_data ):
	global sslenter
	if sslenter:
		exitcode = 4
		raise Exception
	sslenter = True
	return True, trust_data['failures'], True

def get_login( realm, username, may_save ):
	global loginenter
	if loginenter:
		exitcode = 3
		raise Exception
	loginenter = True
	return True, usr, pwd, False

def get_log_message():
	return True, comment

def update(client, location):
	global cleanup
	try:
		client.update(location)
	except pysvn.ClientError, e:
		for message, code in e.args[1]:
			if code == 155004: # locked
				cleanup+=1
				if (cleanup>3):
					raise
				client.cleanup(location)
				update(client, location)
			else:
				raise

def checkin(client, location, comment):
	global cleanup
	try:
		rev = client.checkin([location],comment)
		if rev is not None and rev.number > 0:
			print rev.number
	except pysvn.ClientError, e:
		for message, code in e.args[1]:
			if code == "155004": # locked
				cleanup+=1
				if (cleanup>3):
					raise
				client.cleanup(location)
				checkin(client, location, comment)
			else:
				raise

try:
	client = pysvn.Client()
	client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt
	client.callback_get_login = get_login
	client.callback_get_log_message = get_log_message
	client.exception_style = 1

	if os.path.exists(location):
		update(client, location)
	else:
		client.checkout(url,location)
		os.chmod(location, 0777)

	if len(sys.argv)>3:
		checkin(client, location, comment)

except pysvn.ClientError, e:
	print e.args[0]
	exitcode = 1
except:
	exitcode = 2
finally:
	try:
		client.cleanup(location)
	except:
		none = True
	if exitcode!=0:
		sys.exit(exitcode)

